import cgi
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import datastore
from google.appengine.api import mail

import tvdb
import rpc_admin_methods

class Notification(webapp.RequestHandler):
    def get(self):
        mailFrom = "pytv.series@gmail.com"
        subject = "PyTv: Today Episodes"
        prefs = tvdb.obtain_users_to_notify()
        for user in prefs:
            cals = tvdb.search_today_episodes(user.userId)
            mailTo = str(user.userId.nickname()) + "@gmail.com"
            if cals.count() > 0:
                body = ''
                for cal in cals:
                    body += str(cal.serie).upper() + ' - ' + str(cal.season) + 'x' + str(cal.nroEp) + ': ' + str(cal.episode) + '\n'
                body += '\nVisit PyTv Page tomorrow to obtain the download links.\n'
                body += 'http://pytv-series.appspot.com'
                mail.send_mail(mailFrom, mailTo, subject, body)
                
                
class Downloads(webapp.RequestHandler):
    def get(self):
        tvdb.delete_old_downloads()
        
        
class CleanOld(webapp.RequestHandler):
    def get(self):
        tvdb.delete_old_episodes()
        
        
class RefreshCalendarIncomplete(webapp.RequestHandler):
    def get(self):
        rpc = RPCAdminMethods()
        series = tvdb.find_series_refresh_incomplete()
        for serie in series:
            rpc.ResetSerie(serie)


class RefreshCalendar(webapp.RequestHandler):
    def get(self):
        rpc = RPCAdminMethods()
        series = tvdb.find_series_refresh()
        for serie in series:
            rpc.ResetSerie(serie)        


def main():
    application = webapp.WSGIApplication([
        ('/notification', Notification),
        ('/downloads', Downloads),
        ('/cleanold', CleanOld),
        ('/refreshincomplete', RefreshCalendarIncomplete),
        ('/refresh', RefreshCalendar)
        ], debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
